<script setup>
import exportComponent from './exportComponent.js'
import {message,Modal} from 'ant-design-vue'
import {ref, markRaw, nextTick, onMounted} from 'vue'
import {resumeInfoStore} from "@/stores/modules/resume.js";
import SiderbarMenu from "@/views/resumeCreation/components/SiderbarMenu.vue";
import {getResumeFile, uploadFile} from "@/api/file.js";
import getPdf from "@/utils/htmlToPdf.js";
import {getAllCompany} from "@/views/resumeCreation/components/contentEdit/share.js";

onMounted(()=>{
  getAllCompany()
})

//选中的key
const selectedKey = ref('info');
const open = ref(false);
//文件名
const isModalVisible = ref(false);
const currentFile = ref(null);
const isLoading = ref(false)

// 获取当前日期并格式化为 YYYY-MM-DD
const getCurrentDate = () => {
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
  const day = String(today.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

const generateResume = async () => {
  isLoading.value = true;
  console.log(isLoading.value);
  const resumeElement = document.querySelector('.content-main');

  // 获取到按钮元素
  const editButtons = document.querySelectorAll('.edit-info');
  const addButtons = document.querySelectorAll('.add-info');
  const deleteButtons = document.querySelectorAll('.delete-info');

  // 隐藏所有按钮
  editButtons.forEach(button => button.style.display = 'none');
  addButtons.forEach(button => button.style.display = 'none');
  deleteButtons.forEach(button => button.style.display = 'none');

  // 生成简历 PDF
  if (resumeElement) {
    try {
      await getPdf('个人简历', resumeElement);

      // 恢复按钮显示
      editButtons.forEach(button => button.style.display = 'inline-block');
      addButtons.forEach(button => button.style.display = 'inline-block');
      deleteButtons.forEach(button => button.style.display = 'inline-block');
    } catch (error) {

      // 恢复按钮显示以防生成失败
      editButtons.forEach(button => button.style.display = 'inline-block');
      addButtons.forEach(button => button.style.display = 'inline-block');
      deleteButtons.forEach(button => button.style.display = 'inline-block');
    } finally {
      isLoading.value = false; // 确保无论成功还是失败，都会将 isLoading 设置为 false
    }
  } else {
    console.error('未找到指定的 DOM 元素');
    isLoading.value = false; // 如果未找到元素，也要将 isLoading 设置为 false
  }
};

const fileName = ref(getCurrentDate())
const showModal = () => {
  open.value = true;
};
const handleOk = e => {
  open.value = false;
}

const updateResume = async () => {
  try {
    const res = await getResumeFile();
    if (res.data.code === 200) {
      resumeInfoStore().setResumeInfo(res.data.data);
    } else {
      message.error(res.data.message);
    }
  } catch (e) {
    message.error('出错了');
  }
};

const selectKey = (val) =>{
  selectedKey.value = val
  let element = document.getElementById(val)
  let parent = document.getElementById('parent')
  if(val!=='info'){
    parent.scroll({
      top: element.offsetTop - parent.offsetTop,
      behavior: 'smooth'
    });
  }else {
    document.querySelector(".resume-content").scrollTo({ top: 0, behavior: 'smooth'})
  }
}

const customRequest = async () => {
  const formData = new FormData();
  formData.append('file', currentFile.value);
  try {
    const res = await uploadFile({
      file: currentFile.value,
      fileName: fileName.value
    }, {
      onUploadProgress: ({total,loaded}) => {
        file.onProgress = ({percent: Math.round((loaded/total)*100).toFixed(2)},file)
      }
    });

    if (res.data.code !== 200) {
      throw new Error(res.data.message || '上传失败');
    }
    file.onSuccess(res.data, file);
    //成功，刷新store，
    await updateResume()
  } catch (error) {
    message.error(error.message || '上传出错');
    file.onError(error, file);
  }
};

const handleModalOk = () => {
  if (currentFile) {
    customRequest();
    isModalVisible.value = false; // 关闭对话框
  }
};

const beforeUpload = (file) => {
  const isSupportedType = file.type === 'application/pdf';
  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isSupportedType) {
    message.error('仅支持上传 PDF 格式的文件');
    return false;
  }

  if (!isLt10M) {
    message.error('上传文件大小不能超过 10MB');
    return false;
  }

  currentFile.value = file; // 保存文件对象
  isModalVisible.value = true; // 打开输入文件名对话框
  return false; // 阻止默认上传行为
};

const progress = {
  strokeColor: {
    '0%': '#108ee9',
    '100%': '#87d068',
  },
  strokeWidth: 3,
  format: percent => `${parseFloat(percent.toFixed(2))}%`,
  class: 'test',
};

const sections = ref([
  { key: "info", label: "个人信息", content: "姓名、性别、联系方式等。",
    isEditing: false, component: markRaw(exportComponent.PersonalInformation) },
  { key: "status", label: "求职状态", content: "离职-随时到岗。",
    isEditing: false, component: markRaw(exportComponent.JobSearchStatus) },
  { key: "advantage", label: "个人优势", content: "丰富的个人优势介绍。",
    isEditing: false, component: markRaw(exportComponent.PersonalStrengths) },
  { key: "job", label: "期望职位", content: "全 职职位，安全评价师。",
    isEditing: false, component: markRaw(exportComponent.DesiredPosition) },
  // { key: "city", label: "工作城市", content: "北京、上海等一线城市。",
  //   isEditing: false, component: markRaw(exportComponent.WorkCity) },
  { key: "work", label: "工作经历", content: "详细的工作经历列表。",
    isEditing: false, component: markRaw(exportComponent.WorkExperience) },
  { key: "projects", label: "项目经验", content: "项目经验描述。",
    isEditing: false, component: markRaw(exportComponent.ProjectExperience) },
  { key: "education", label: "教育经历", content: "湖南大学软件工程专业。",
    isEditing: false, component: markRaw(exportComponent.EducationalExperience) },
]);
</script>

<template>
  <div class="resume-page"
       v-loading.fullscreen.lock="isLoading"
       element-loading-text="简历制作中，请耐心等待...">
    <div class="main-container">
      <div class="sidebar">
        <SiderbarMenu :menuItems="sections" @selectKey="selectKey"/>
      </div>
      <div class="resume-content" id="parent">
        <div class="content-header">
          <div style="color: #85898c">我的在线简历</div>
          <div style="color: #1890ff;gap:10px">
            <a-button type="link" @click="generateResume">生成简历</a-button>
            <a-button type="link" @click="showModal">导入已有简历</a-button>
          </div>
        </div>
        <div class="content-main">
          <section
              v-for="section in sections"
              :key="section.key"
              :id="section.key">
            <component
                :is="section.component"/>
          </section>
          <a-modal
              v-model:open="open"
              @ok="handleOk"
              ok-text="确认"
              cancel-text="取消"
              centered>
            <a-upload-dragger
                name="file"
                :custom-request="customRequest"
                :before-upload="beforeUpload"
                :progress="progress"
                :maxCount="1"
            >
              <p class="ant-upload-drag-icon">
                <inbox-outlined></inbox-outlined>
              </p>
              <p class="ant-upload-text">选择或者拖拽一个文件上传</p>
              <p class="ant-upload-hint">
                可以上传PDF,DOC,DOCX格式的文件，大小不超过10M
              </p>
            </a-upload-dragger>
          </a-modal>
          <!-- 对话框 -->
          <a-modal v-model:open="isModalVisible" title="输入文件名" @ok="handleModalOk">
            <a-input v-model:value="fileName" placeholder="请输入文件名" />
          </a-modal>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.resume-page {
  width: 100%;
  height: calc(100% - 88px);
  background-color: #ffffff;
}

.main-container {
  width: 1200px;
  height: 100%;
  display: flex;
  margin: 0 auto;
}

.sidebar {
  flex: 0 0 200px;
  background-color: #ffffff;
}

.resume-content {
  flex: 1;
  right: 0;
  overflow-y: scroll;
  margin: 0 20px;
  border-radius: 10px;
  background-color: white;
  scrollbar-width: none;
}

.content-main {
  padding: 20px 10px;
  overflow: hidden;
  >section {
    margin-bottom: 20px;
    border-bottom: 1px solid #f0f0f0;
    border-radius: 10px;
  }
}

.content-header {
  background-color: #f1f9ff;
  height: 50px;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  >div{
    display: flex;
  }
}

.settings {
  flex: 0 0 250px;
  background-color: #f5f6fa;
}
</style>